//
//  SoundView.m
//  DJS
//
//  Created by 浪尖渝力 on 2018/1/22.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "SoundView.h"
#import "SD_RecordHelper.h"

@implementation SoundView

-(void)creatView{
    
    self.backgroundColor=_LightGrey;
    _timeTick=0;
    _abc=0;
    UIImageView *beiJing=[UIImageView new];
    [self addSubview:beiJing];
    [beiJing mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(_mainH*0.5);
    }];
    beiJing.image=[UIImage imageNamed:@"录音背景"];
    
    UIImageView *timeImage=[UIImageView new];
    [beiJing addSubview:timeImage];
    [timeImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(_mainH*0.15);
        make.height.with.mas_equalTo(_mainW*0.4);
    }];
    timeImage.image=[UIImage imageNamed:@"录音圆"];
    
    _timeLabel1=[UILabel new];
    [timeImage addSubview:_timeLabel1];
    [_timeLabel1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
    }];
    _timeLabel1.text=@"00:00";
    _timeLabel1.textColor=ColorWithRGB(49, 49, 49);
    _timeLabel1.font=[UIFont systemFontOfSize:17];
    
    UIView *centerView=[UIView new];
    [self addSubview:centerView];
    [centerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.height.mas_equalTo(150);
        make.top.mas_equalTo(beiJing.mas_bottom).mas_equalTo(-50);
    }];
    centerView.layer.cornerRadius=5;
    centerView.backgroundColor=[UIColor whiteColor];
    
    _luYingImge=[UIImageView new];
    [centerView addSubview:_luYingImge];
    [_luYingImge mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
        make.width.height.mas_equalTo(50);
    }];
    _luYingImge.image=[UIImage imageNamed:@"播放"];
    _luYingImge.userInteractionEnabled=YES;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(LuYing:)];
    [_luYingImge addGestureRecognizer:tapGesture];
    
    _label=[UILabel new];
    [centerView addSubview:_label];
    [_label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(_luYingImge);
        make.top.mas_equalTo(_luYingImge.mas_bottom).mas_equalTo(20);
    }];
    _label.textColor=ColorWithRGB(149, 149, 149);
    _label.text=@"录音";
    _label.font=[UIFont systemFontOfSize:17];
    
    
    UIImageView *luYing2=[UIImageView new];
    [centerView addSubview:luYing2];
    [luYing2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.centerX.mas_equalTo(-_mainW/3);
        make.width.height.mas_equalTo(50);
    }];
    luYing2.image=[UIImage imageNamed:@"重录"];
    
    luYing2.userInteractionEnabled=YES;
    UITapGestureRecognizer *tapGesture2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ChongLu:)];
    [luYing2 addGestureRecognizer:tapGesture2];
    
    UILabel *label2=[UILabel new];
    [centerView addSubview:label2];
    [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(luYing2);
        make.top.mas_equalTo(luYing2.mas_bottom).mas_equalTo(20);
    }];
    label2.textColor=ColorWithRGB(149, 149, 149);
    label2.text=@"重录";
    label2.font=[UIFont systemFontOfSize:17];
    
    
    UIImageView *luYing3=[UIImageView new];
    [centerView addSubview:luYing3];
    [luYing3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.centerX.mas_equalTo(_mainW/3);
        make.width.height.mas_equalTo(50);
    }];
    luYing3.image=[UIImage imageNamed:@"完成"];
    
    luYing3.userInteractionEnabled=YES;
    UITapGestureRecognizer *tapGesture3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(wanCheng:)];
    [luYing3 addGestureRecognizer:tapGesture3];
    
    
    UILabel *label3=[UILabel new];
    [centerView addSubview:label3];
    [label3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(luYing3);
        make.top.mas_equalTo(luYing3.mas_bottom).mas_equalTo(20);
    }];
    label3.textColor=ColorWithRGB(149, 149, 149);
    label3.text=@"完成";
    label3.font=[UIFont systemFontOfSize:17];
    
    
    UILabel *label4=[UILabel new];
    [self addSubview:label4];
    [label4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(centerView.mas_bottom).mas_equalTo(20);
    }];
    label4.text=@"录音试听";
    label4.textColor=ColorWithRGB(49, 49, 49);
    label4.font=[UIFont systemFontOfSize:17];
    
    
    NSData *Data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.djiaoshou.com/yuyin.gif"]];
    UIImage *image=[UIImage imageWithData:Data];
    
    _shiTing=[UIImageView new];
    [self addSubview:_shiTing];
    [_shiTing mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(40/image.size.height*image.size.width);
        make.top.mas_equalTo(label4.mas_bottom).mas_equalTo(30);
    }];
    _shiTing.image=[UIImage imageNamed:@"录音"];
    _shiTing.userInteractionEnabled=YES;
    UITapGestureRecognizer *tapGesture4 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushToShiTing:)];
    [_shiTing addGestureRecognizer:tapGesture4];
    
    
    _timeLabel2=[UILabel new];
    [self addSubview:_timeLabel2];
    [_timeLabel2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(_shiTing);
        make.left.mas_equalTo(_shiTing.mas_right).mas_equalTo(20);
    }];
    _timeLabel2.textColor=ColorWithRGB(149, 149, 149);
    _timeLabel2.font=[UIFont systemFontOfSize:17];
    _timeLabel2.text=@"00‘";
    
    UIButton *btn=[UIButton new];
    [self addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.bottom.mas_equalTo(-30);
        make.width.mas_equalTo(centerView);
        make.height.mas_equalTo(50);
    }];
    btn.backgroundColor=ColorWithRGB(183, 157, 108);
    btn.layer.cornerRadius=10;
    [btn setTitle:@"确认上传" forState:0];
    [btn setTitleColor:[UIColor whiteColor] forState:0];
    [btn addTarget:self action:@selector(tijiao:) forControlEvents:UIControlEventTouchUpInside];
    
}
-(IBAction)tijiao:(id)sender{
  
    
    if (_abc==0) {
        [ZQTools svpInfo:@"你还没有录音，请先录音"];
        return;
    }
    if (_abc==1) {
        [ZQTools svpInfo:@"正在录音，不能提交"];
        return;
    }
    
    if (_abc==2) {
        [ZQTools svpInfo:@"请先点击完成才能提交"];
        return;
    }
    
    NSArray *arr=[NSArray arrayWithObject:[_recordHelper getSavePath]];
    
    NSDictionary *userDic = [NSKeyedUnarchiver unarchiveObjectWithFile:_userModelFile];
    NSString *token=[userDic objectForKey:@"token"];
    NSNumber *waiter_id1=[userDic objectForKey:@"waiter_id"];
    NSString *waiter_id=[NSString stringWithFormat:@"%@",waiter_id1];
    
    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%@",_consult_id],@"consult_id",waiter_id,@"waiter_id",[NSString stringWithFormat:@"%d",_timeTick],@"sl_time_long",token,@"token",@"1",@"user_role", nil];
    [ZQTools afnPostImageWithDict:dic WithAddressUrl:@"waiter/consult/replay" withImageArr:arr withFileName:@"replay_file" fileOrImg:@"file" WithViewController:self.viewController success:^(id responseObject) {
        [ZQTools svpInfo:@"上传成功"];
        [self.viewController.navigationController popViewControllerAnimated:YES];
        
        NSLog(@"%@",responseObject);
    }];
}
-(void)ChongLu:(UITapGestureRecognizer *)tap{
    _abc=0;
    _label.text=@"录音";
    _luYingImge.image=[UIImage imageNamed:@"播放"];
    [_recordHelper finishRecord];
    _timeTick=0;
    _timeLabel2.text=[NSString stringWithFormat:@"%d‘",_timeTick];
    if (_timeTick<10) {
        _timeLabel1.text=[NSString stringWithFormat:@"00:0%d",_timeTick];
    }
    if (_timeTick<60&&_timeTick>=10) {
        _timeLabel1.text=[NSString stringWithFormat:@"00:%d",_timeTick];
    }
    [_timer invalidate];
    
}

-(void)wanCheng:(UITapGestureRecognizer *)tap{
    _abc=3;
    _label.text=@"录音";
    _luYingImge.image=[UIImage imageNamed:@"播放"];
    [_recordHelper finishRecord];
    [_timer invalidate];
}
-(void)LuYing:(UITapGestureRecognizer *)tap{
    
    
    AVAuthorizationStatus videoAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (videoAuthStatus == AVAuthorizationStatusNotDetermined) {// 未询问用户是否授权
        //第一次询问用户是否进行授权
        [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
            // CALL YOUR METHOD HERE - as this assumes being called only once from user interacting with permission alert!
            if (granted) {
                
            }
            else {
                
            }
        }];
    }
    else if(videoAuthStatus == AVAuthorizationStatusRestricted || videoAuthStatus == AVAuthorizationStatusDenied) {// 未授权
        [self showSetAlertView];
    }
    else{// 已授权
        [self sagffh];
    }
    
    
}
//提示用户进行麦克风使用授权
- (void)showSetAlertView {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"麦克风权限未开启" message:@"麦克风权限未开启，请进入系统【设置】>【隐私】>【麦克风】中打开开关,开启麦克风功能" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *setAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //跳入当前App设置界面
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }];
    [alertVC addAction:cancelAction];
    [alertVC addAction:setAction];
    
    [self.viewController presentViewController:alertVC animated:YES completion:nil];
}


-(void)sagffh{
    if ([_label.text isEqualToString:@"录音"]){
        if (_abc==1) {
            return;
        }
        _abc=1;
        _timeTick=0;
        _recordHelper=[SD_RecordHelper share];
        [_recordHelper startRecord];
        _label.text=@"暂停";
        _luYingImge.image=[UIImage imageNamed:@"暂停"];
        _timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(creatDongHu) userInfo:nil repeats:YES];
        return;
        
    }
    if ([_label.text isEqualToString:@"继续"]){
        
        _abc=1;
        [_recordHelper resumeRecord];
        _label.text=@"暂停";
        _luYingImge.image=[UIImage imageNamed:@"暂停"];
        _timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(creatDongHu) userInfo:nil repeats:YES];
        
        return;
    }
    
    if ([_label.text isEqualToString:@"暂停"]) {
        _label.text=@"继续";
        _luYingImge.image=[UIImage imageNamed:@"播放"];
        _abc=2;
        [_timer invalidate];
        [_recordHelper pauseRecord];
        
        return;
    }
    
    
}
-(void)creatDongHu{
    if (_timeTick>=120) {
        [_recordHelper finishRecord];
        [_timer invalidate];
    }
    
    if (_timeTick<10) {
        _timeLabel1.text=[NSString stringWithFormat:@"00:0%d",_timeTick];
    }
    if (_timeTick<60&&_timeTick>=10) {
        _timeLabel1.text=[NSString stringWithFormat:@"00:%d",_timeTick];
    }
    if (_timeTick>60) {
        int y=_timeTick%60;
        int x=_timeTick/60;
        if (x<10) {
            if (y<10) {
                _timeLabel1.text=[NSString stringWithFormat:@"0%d:0%d",x,y];
            }
            if (_timeTick<60&&_timeTick>=10) {
                _timeLabel1.text=[NSString stringWithFormat:@"0%d:%d",x,y];
            }
        }
        else{
            if (y<10) {
                _timeLabel1.text=[NSString stringWithFormat:@"%d:0%d",x,y];
            }
            if (_timeTick<60&&_timeTick>=10) {
                _timeLabel1.text=[NSString stringWithFormat:@"%d:%d",x,y];
            }
            
        }
        
    }
    _timeLabel2.text=[NSString stringWithFormat:@"%d‘",_timeTick];
    _timeTick++;
    
}

-(void)pushToShiTing:(UITapGestureRecognizer *)tap{
    if (_abc==1||_abc==2) {
        [ZQTools svpInfo:@"请先点击完成才能试听"];
        return;
    }
    if (_abc==0) {
        [ZQTools svpInfo:@"请先录音才能试听"];
        return;
    }
    
    NSString  *name = @"yuyin.gif";
    NSString  *filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]] pathForResource:name ofType:nil];
    NSData  *imageData = [NSData dataWithContentsOfFile:filePath];
    _shiTing.image= [UIImage sd_animatedGIFWithData:imageData];
    
    _timer2=[NSTimer scheduledTimerWithTimeInterval:_timeTick target:self selector:@selector(creatDongHu2) userInfo:nil repeats:YES];
    _shiTing.userInteractionEnabled=NO;
    [_recordHelper playRecord:[NSString stringWithFormat:@"%@",[_recordHelper getSavePath]]];
}
-(void)creatDongHu2{
    _shiTing.image=[UIImage imageNamed:@"录音"];
    _shiTing.userInteractionEnabled=YES;
    [_timer2 invalidate];
}
@end
